package cn.gpnusz.ucloudteach.controller.live.admin;

import cn.dev33.satoken.stp.StpUtil;
import cn.gpnusz.ucloudteach.common.CommonResp;
import cn.gpnusz.ucloudteach.entity.Admin;
import cn.gpnusz.ucloudteach.entity.LiveTokenResp;
import cn.gpnusz.ucloudteach.service.course.CourseService;
import cn.gpnusz.ucloudteach.service.live.LiveContentServiceImpl;
import cn.gpnusz.ucloudteach.service.user.SuperAdminService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * @author h0ss
 * @description 教师直播api
 * @date 2022/4/6 - 14:16
 */
@RestController
@RequestMapping("/api/admin/live")
public class AdminLiveController {

    @Resource
    private CourseService courseService;

    @Resource
    private SuperAdminService adminService;

    @Resource
    private LiveContentServiceImpl liveContentService;

    /**
     * 教师开始直播
     *
     * @return : cn.gpnusz.ucloudteach.common.CommonResp<cn.gpnusz.ucloudteach.entity.LiveTokenResp>
     * @author h0ss
     */
    @PostMapping("/begin")
    public CommonResp<LiveTokenResp> startLive(@RequestBody Map<String, Long> courseAndContentReq) {
        CommonResp<LiveTokenResp> resp = new CommonResp<>();
        Long courseId = courseAndContentReq.get("courseId");
        // 根据id查询用户名
        Long userId = StpUtil.getLoginIdAsLong();
        Admin info = adminService.getInfoById(userId);
        // 判断用户是否为开课教师
        if (info == null || !courseService.checkTeacher(info.getUsername(), courseId)) {
            resp.setSuccess(false);
            resp.setMessage("请求受限：非开课教师");
            return resp;
        }
        return liveContentService.startLive(userId, courseId);
    }

    /**
     * 教师结束直播
     *
     * @param courseAndContentReq : 课程id & 课时id
     * @return : cn.gpnusz.ucloudteach.common.CommonResp<java.lang.Object>
     * @author h0ss
     */
    @PostMapping("/finish")
    public CommonResp<Object> finishLive(@NotNull @RequestBody Map<String, Long> courseAndContentReq) {
        CommonResp<Object> resp = new CommonResp<>();
        Long courseId = courseAndContentReq.get("courseId");
        Long contentId = courseAndContentReq.get("contentId");
        liveContentService.finishLive(courseId, contentId);
        resp.setMessage("直播已结束，回放正在生成");
        return resp;
    }
}
